import java.util.*;
/**
 * Created With IntelliJ IDEA
 * Description:牛客网:BM5 合并k个已排序的链表
 * <a href="https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6?tpId=295&tqId=724&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj">...</a>
 * User: DELL
 * Data: 2023-03-20
 * Time: 13:17
 */

//总结:该题基于分治法的解法优于基于PriorityQueue实现的
public class Solution {
    private static class ListNode {
        int val;
        ListNode next;
        public ListNode(int val) {
            this.val = val;
        }
    }

    /**
     * 方法一:基于PriorityQueue实现
     * @param lists
     * @return
     */
    public ListNode mergeKLists(ArrayList<ListNode> lists) {
        //判空处理
        if (lists == null) {
            return null;
        }
        //建立小根堆
        PriorityQueue<ListNode> heap = new PriorityQueue<>((o1,o2) -> o1.val - o2.val);
        for (ListNode list : lists) {
            if (list != null) {
                heap.add(list);
            }
        }
        ListNode head = new ListNode(-1);
        ListNode cur = head;
        while (!heap.isEmpty()) {
            ListNode temp = heap.poll();
            cur.next = temp;
            cur = cur.next;
            if (temp.next != null) {
                heap.add(temp.next);
            }
        }
        return head.next;
    }
    /**
     * 方法二:基于分治(归并排序)的思想
     */
    public ListNode mergeKLists2(ArrayList<ListNode> lists) {
        //判空处理
        if (lists.isEmpty()) {
            return null;
        }
        return divideMerge(lists,0,lists.size()-1);
    }
    private ListNode divideMerge(ArrayList<ListNode> lists, int left, int right) {
        if (left >= right) {
            return lists.get(left);
        }
        int mid = (left + right) / 2;
        ListNode head1 = divideMerge(lists,left,mid);
        ListNode head2 = divideMerge(lists,mid+1,right);
        return merge(head1,head2);
    }
    private ListNode merge(ListNode head1, ListNode head2) {
        //判空处理
        if (head1 == null) {
            return head2;
        }
        if (head2 == null) {
            return head1;
        }
        ListNode newHead = new ListNode(-1);
        ListNode cur = newHead;
        while (head1 != null && head2 != null) {
            if (head1.val < head2.val) {
                cur.next = head1;
                cur = cur.next;
                head1 = head1.next;
            } else {
                cur.next = head2;
                cur = cur.next;
                head2 = head2.next;
            }
        }
        //连接剩余结点
        if (head1 == null) {
            cur.next = head2;
        } else {
            cur.next = head1;
        }
        return newHead.next;
    }
}